package com.sinodata.bsm.cicp.collector.weblogic9;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import weblogic.health.HealthState;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: Weblogic9及以上版本JTA指标采集程序
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Jun 22, 2011 4:31:14 PM  liulibo        1.1.0       To create
 * Oct 31, 2011 4:25:05 PM  liulibo        1.1.1       增加 超时回滚事务数、资源错误回滚事务数 
 *                                                     应用程序错误回滚事务数、系统错误回滚事务数
 *                                                     所有提交事物的总秒数、已放弃事物数、健康状况 指标
 * Nov 4,2011   3:39:05 PM  liulibo        1.1.2       修改事物回滚比率算法  原算法：两次采集TransactionRolledBackTotalCount差值*100/TransactionTotalCount
 *                                                     新算法：两次采集TransactionRolledBackTotalCount差值*100/TransactionTotalCount两次采集差值
 *                                                     但是还有问题，应该时多长时间内事物回滚比率才正确。
 * </p>
 *
 * @since 
 * @see
 */
public class JtaCollector extends Collector {

    private static final Logger logger = Logger.getLogger(JtaCollector.class);

    private final HashMap<String, String> lastTransactionRolledBackTotalCount = new HashMap<String, String>();

    private final HashMap<String, String> lastTransactionTotalCount = new HashMap<String, String>();

    /**
     * 执行采集
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        String serversName = this.getParamMap().get("ServerName").trim();
        String port = this.getParamMap().get("port").trim();
        String key = serversName + ":" + ip;
        ObjectName service;
        String name = null;
        Object attrValues[] = null;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            ObjectName[] serverRuntimes = (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
            for (ObjectName objectName : serverRuntimes) {
                name = objectName.getKeyProperty("Name");
                if (name.equals(serversName)) {
                    Object jtaRuntime = connection.getAttribute(objectName, "JTARuntime");
                    String attributeNames[] = new String[] { "ActiveTransactionsTotalCount", "TransactionCommittedTotalCount", "TransactionHeuristicsTotalCount", "TransactionTotalCount", "TransactionRolledBackTotalCount", "TransactionRolledBackTimeoutTotalCount", "TransactionRolledBackResourceTotalCount", "TransactionRolledBackAppTotalCount", "TransactionRolledBackSystemTotalCount", "SecondsActiveTotalCount", "TransactionAbandonedTotalCount", "HealthState" };
                    attrValues = JmxUtil.getAttribute(connection, (ObjectName) jtaRuntime, attributeNames);
                    for (int i = 0; i < attrValues.length - 1; i++) {
                        propValues[i] = ResPropertyValue.createPropValue(attrValues[i].toString(), propMetas[i]);
                    }
                    String serverHealth = "UNKNOWN";
                    if (attrValues.length >= 12 && attrValues[11] != null && attrValues[11] instanceof HealthState) {
                        HealthState healthState = (HealthState) attrValues[11];
                        int serverHealthState = healthState.getState();
                        if (serverHealthState == HealthState.HEALTH_OK) {
                            serverHealth = "OK";
                        } else if (serverHealthState == HealthState.HEALTH_WARN) {
                            serverHealth = "WARN";
                        } else if (serverHealthState == HealthState.HEALTH_CRITICAL) {
                            serverHealth = "CRITICAL";
                        } else if (serverHealthState == HealthState.HEALTH_FAILED) {
                            serverHealth = "FAILED";
                        }
                    }
                    propValues[11] = ResPropertyValue.createPropValue(serverHealth, propMetas[11]);
                }
            }
        } catch (Exception e) {
            logger.error("failed to collect by JtaCollector", e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        String transactionRolledBackRatio = "";
        if (lastTransactionRolledBackTotalCount.get(key) != null && lastTransactionTotalCount.get(key) != null) {
            long rbTemp = Long.parseLong(String.valueOf(lastTransactionRolledBackTotalCount.get(key)));
            long temp = Long.parseLong(String.valueOf(lastTransactionTotalCount.get(key)));
            if (Long.parseLong(attrValues[3].toString()) <= 0) {
                transactionRolledBackRatio = transactionRolledBackRatio + 0;
            } else {
                transactionRolledBackRatio = "" + ((Long.parseLong(attrValues[4].toString()) - rbTemp) * 100) / (Long.parseLong(attrValues[3].toString()) - temp);
            }
            if (Long.parseLong(transactionRolledBackRatio) < 0) {
                transactionRolledBackRatio = "0";
            }
        } else {
            lastTransactionRolledBackTotalCount.remove(key);
            lastTransactionRolledBackTotalCount.put(key, attrValues[4].toString());
            lastTransactionTotalCount.remove(key);
            lastTransactionTotalCount.put(key, attrValues[4].toString().toString());
            transactionRolledBackRatio = "0";
        }
        propValues[12] = ResPropertyValue.createPropValue(transactionRolledBackRatio, propMetas[12]);
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    /**
     * 采集参数定义
     */
    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerName", "port" };
    }

    /**
     * 采集字段定义
     */
    @Override
    public String[] getPropMeta() {
        //return new String[] { "ActiveTransactionsTotalCount", "TransactionCommittedTotalCount", "TransactionHeuristicsTotalCount", "TransactionTotalCount", "TransactionRolledBackTotalCount", "TransactionRolledBackTimeoutTotalCount", "TransactionRolledBackResourceTotalCount", "TransactionRolledBackAppTotalCount", "TransactionRolledBackSystemTotalCount", "SecondsActiveTotalCount", "TransactionAbandonedTotalCount", "HealthState", "TransactionRolledBackRatio" };
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13" };

    }

}
